package com.example.research.controller;

import com.example.research.dto.ApiResponse;
import com.example.research.entity.Paper;
import com.example.research.service.AuthService;
import com.example.research.service.PaperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDate;
import java.util.List;

/**
 * 论文控制器
 */
@RestController
@RequestMapping("/papers")
@Validated
public class PaperController {

    @Autowired
    private PaperService paperService;

    @Autowired
    private AuthService authService;

    /**
     * 获取当前用户ID
     */
    private Long getCurrentUserId(String authHeader) {
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            throw new RuntimeException("未提供有效的认证信息");
        }
        String token = authHeader.substring(7);
        return authService.getUserIdFromToken(token);
    }

    /**
     * 查询所有论文
     */
    @GetMapping
    public ApiResponse<List<Paper>> getAllPapers() {
        try {
            List<Paper> papers = paperService.findAll();
            return ApiResponse.success(papers);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据ID查询论文
     */
    @GetMapping("/{id}")
    public ApiResponse<Paper> getPaperById(@PathVariable Long id) {
        try {
            Paper paper = paperService.findById(id);
            if (paper == null) {
                return ApiResponse.notFound("论文不存在");
            }
            return ApiResponse.success(paper);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 查询当前用户的论文
     */
    @GetMapping("/my")
    public ApiResponse<List<Paper>> getMyPapers(@RequestHeader("Authorization") String authHeader) {
        try {
            Long userId = getCurrentUserId(authHeader);
            List<Paper> papers = paperService.findByUserId(userId);
            return ApiResponse.success(papers);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据审核状态查询论文
     */
    @GetMapping("/audit-status/{status}")
    public ApiResponse<List<Paper>> getPapersByAuditStatus(@PathVariable Integer status) {
        try {
            List<Paper> papers = paperService.findByAuditStatus(status);
            return ApiResponse.success(papers);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据期刊查询论文
     */
    @GetMapping("/journal/{journalName}")
    public ApiResponse<List<Paper>> getPapersByJournal(@PathVariable String journalName) {
        try {
            List<Paper> papers = paperService.findByJournal(journalName);
            return ApiResponse.success(papers);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据检索级别查询论文
     */
    @GetMapping("/index-level/{indexLevel}")
    public ApiResponse<List<Paper>> getPapersByIndexLevel(@PathVariable String indexLevel) {
        try {
            List<Paper> papers = paperService.findByIndexLevel(indexLevel);
            return ApiResponse.success(papers);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据作者查询论文
     */
    @GetMapping("/author/{author}")
    public ApiResponse<List<Paper>> getPapersByAuthor(@PathVariable String author) {
        try {
            List<Paper> papers = paperService.findByAuthor(author);
            return ApiResponse.success(papers);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据条件查询论文
     */
    @GetMapping("/search")
    public ApiResponse<List<Paper>> searchPapers(
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String journalName,
            @RequestParam(required = false) String indexLevel,
            @RequestParam(required = false) Integer auditStatus,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        try {
            List<Paper> papers = paperService.findByConditions(
                    userId, journalName, indexLevel, auditStatus, startDate, endDate);
            return ApiResponse.success(papers);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 创建论文
     */
    @PostMapping
    public ApiResponse<Paper> createPaper(@Valid @RequestBody Paper paper,
                                        @RequestHeader("Authorization") String authHeader) {
        try {
            Long userId = getCurrentUserId(authHeader);
            paper.setUserId(userId);
            Paper createdPaper = paperService.createPaper(paper);
            return ApiResponse.success("论文创建成功", createdPaper);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 更新论文
     */
    @PutMapping("/{id}")
    public ApiResponse<Paper> updatePaper(@PathVariable Long id,
                                        @Valid @RequestBody Paper paper,
                                        @RequestHeader("Authorization") String authHeader) {
        try {
            Long userId = getCurrentUserId(authHeader);
            paper.setId(id);
            paper.setUserId(userId);
            Paper updatedPaper = paperService.updatePaper(paper);
            return ApiResponse.success("论文更新成功", updatedPaper);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 删除论文
     */
    @DeleteMapping("/{id}")
    public ApiResponse<String> deletePaper(@PathVariable Long id,
                                         @RequestHeader("Authorization") String authHeader) {
        try {
            Long userId = getCurrentUserId(authHeader);
            paperService.deletePaper(id, userId);
            return ApiResponse.success("论文删除成功");
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 提交审核
     */
    @PostMapping("/{id}/submit")
    public ApiResponse<String> submitForAudit(@PathVariable Long id,
                                            @RequestHeader("Authorization") String authHeader) {
        try {
            Long userId = getCurrentUserId(authHeader);
            paperService.submitForAudit(id, userId);
            return ApiResponse.success("论文提交审核成功");
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
}
